<?php

namespace app\admin\service;

use app\admin\dao\ConsultingMessageDao;
use app\admin\model\UM as UM;
use app\common\model\Consulting;
use app\common\model\ConsultingMessage;
use app\index\service\MessageContentService;
use think\Collection;

/**
 * Class MessageService
 * @package app\admin\service
 */
class MessageService
{
    // dao
    private ConsultingMessageDao $consultingMessageDao;

    public function __construct(ConsultingMessageDao $consultingMessageDao)
    {
        $this->consultingMessageDao = $consultingMessageDao;
    }

    /**
     * 列表
     * @param UM|null $user
     * @param int|null $page
     * @param int|null $page_size
     * @return Collection
     */
    public function index(?UM $user, $type, $consultingId, ?int $page = null, ?int $page_size = null): Collection
    {
        $consulting = Consulting::where('id', $consultingId)->find();

        if (!$consulting) {
            return \think\model\Collection::make();
        }

        if ($type == 0) {
            $memberId = $consulting->memberId;
        } else {
            $memberId = $consulting->lawyerId;
        }

        $collection = $this->consultingMessageDao->select($memberId, $consultingId, $page, $page_size);

        // 前端要倒序的
        $collection = $collection->reverse();

        $this->getMessageContentService()->wrapDynamicMessages($collection);


        $collection->each(function (ConsultingMessage $record) use ($type) {
            $record->isMy = $record->senderType == 'member' && $record->senderMemberType == $type ? '101' : '102';
        });

        return $collection;
    }

    private function getMessageContentService(): MessageContentService
    {
        return app(MessageContentService::class);
    }

}
